package com.icbc.api;

import com.jcraft.jsch.*;

import java.util.logging.Logger;

public class TestStfp {

    public static void main(String[] args) {


        String host = "106.120.68.125";
        int port = 8001;
        String user = "qwe43";
        String privateKey = "C:\\Users\\fan\\Desktop\\id_rsa";
        String remoteFilePath = "/JftNetAccAcquire/upload";
        String localFilePath = "C:\\Users\\fan\\Desktop\\a.txt";

        Session session = null;
        ChannelSftp channelSftp = null;

        try {

            JSch jsch = new JSch();
            System.out.println("获取SFTP服务器连接username:{},host:{},port:{}" + user + host + port);
            session = jsch.getSession(user,host,port);
            System.out.println("连接成功建立");



            // 禁用主机密钥检查（不安全，仅用于示例）
            // 在生产环境中，你应该使用JSch的KnownHosts类来检查主机密钥
            java.util.Properties config = new java.util.Properties();
//            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);

            session.connect();

            System.out.println("Connected to " + host + " port " + port);

            // 打开SFTP通道
            channelSftp = (ChannelSftp) session.openChannel("sftp");
            channelSftp.connect();

            // 上传文件到SFTP服务器
            channelSftp.put(localFilePath, remoteFilePath);

//            // 从SFTP服务器下载文件
//            InputStream in = channelSftp.get(remoteFilePath);
//            File localFile = new File(localFilePath);
//            try (OutputStream out = new FileOutputStream(localFile)) {
//                byte[] tmp = new byte[1024];
//                int i;
//                while ((i = in.read(tmp)) != -1) {
//                    out.write(tmp, 0, i);
//                }
//            } catch (FileNotFoundException e) {
//                e.printStackTrace();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }

        } catch (JSchException | SftpException e) {
            e.printStackTrace();
        } finally {
            if (channelSftp != null) {
                channelSftp.disconnect();
            }
            if (session != null) {
                session.disconnect();
            }
        }
    }

}
